<template>
  <div>
    <p style="font-size: 20px">{{ msg }}</p>
    <!--  显示用户列表-->
    <el-table style="width: 100%" :data="pagedUser">
      <!--      表单目录-->
      <el-table-column prop="new_i" label="编号" width="80"/>
      <el-table-column prop="name" label="名称"/>
      <el-table-column prop="pwd" label="密码"/>
      <el-table-column prop="role" label="角色"/>
      <el-table-column align="right">
        <!--        delete与edit的实现-->
        <!--        Delete button -->
        <template #default="scope" v-if="haspermission(['admin','manager'])">
          <div style="display: flex;align-items: center;">
            <!-- Edit button with popover -->
            <el-button size="small" type="danger" @click="open_delete(scope.row)">Delete</el-button>
            <el-popover placement="right" :width="320" trigger="click">
              <template #reference>
                <el-button size="small" @click="setValue(scope.row)">Edit</el-button>
              </template>
              <div>
                <form @submit="handleEdit">
                  <p>向后端数据库修改用户数据:</p>
                  <label>角色：</label>
                  <el-radio-group v-model="UserEdit.role">
                    <el-radio label="admin">管理员</el-radio>
                    <el-radio label="manager">经理</el-radio>
                    <el-radio label="user">员工</el-radio>
                  </el-radio-group>
                  <div style="margin: 10px 0"/>
                  <label>名字：</label>
                  <el-input
                      v-model="UserEdit.name"
                      style="width: 240px"
                      maxlength="10"
                      show-word-limit
                      type="text"
                  />
                  <div style="margin: 10px 0"/>
                  <label>密码：</label>
                  <el-input
                      v-model="UserEdit.pwd"
                      maxlength="10"
                      style="width: 240px"
                      show-word-limit
                      type="text"
                  />
                  <div style="margin: 20px 0"/>
                  <el-button type="info" round @click="handleEdit(scope.row)" size="small">提交修改</el-button>
                </form>
              </div>
            </el-popover>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        style="margin-top: 30px"
        layout="prev, pager, next"
        :total="total"
        v-model="currentPage"
        :page-size="pageSize"
        @current-change="handlePageChange"
    />
    <!--  添加用户数据的表单-->
    <div style="display: flex; align-items: center;">
      <form @submit="UserSubmit" ref="myForm">
        <h3>向后端数据库添加用户数据:</h3>
        <label>名字：</label>
        <el-input
            v-model="inputUser.name"
            style="width: 240px"
            maxlength="10"
            show-word-limit
            type="text"
        />
        <div style="margin: 10px 0"/>
        <label>密码：</label>
        <el-input
            v-model="inputUser.pwd"
            maxlength="10"
            style="width: 240px"
            show-word-limit
            type="text"
        />
        <div style="margin: 10px 0"/>
        <div>
          <el-select v-model="inputUser.role" placeholder="角色"
                     style="background-color: darkslategrey; color: #fff;">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </div>
        <el-button type="success" round @click="UserSubmit">提交数据</el-button>
      </form>
        <div style="padding: 5%"></div>
        <div>
          <h3>查询用户的表单1</h3>
          <label>用户名称：</label>
          <el-input type="text" style="width: 240px" v-model="name_pattern"/>
          <div style="margin: 20px 0"/>
          <el-popover placement="right" :width="600" trigger="click">
            <template #reference>
              <el-button type="info" @click="findUser">按名称查找</el-button>
            </template>
            <el-table :data="suser">
              <el-table-column prop="new_i" label="编号" width="80"/>
              <el-table-column prop="name" label="名称"/>
              <el-table-column prop="pwd" label="密码"/>
              <el-table-column prop="role" label="角色"/>
            </el-table>
          </el-popover>
        </div>
        <div style="padding: 5%"></div>
        <div>
          <h3>查询用户的表单2</h3>
          <label>用户类别：</label>
          <el-input type="text" style="width: 240px" v-model="role"/>
          <div style="margin: 20px 0"/>
          <el-popover placement="right" :width="600" trigger="click">
            <template #reference>
              <el-button type="info" @click="findUser2">按角色查找</el-button>
            </template>
              <el-table :data="suser">
                <el-table-column prop="new_i" label="编号" width="80"/>
                <el-table-column prop="name" label="名称"/>
                <el-table-column prop="pwd" label="密码"/>
                <el-table-column prop="role" label="角色"/>
              </el-table>
          </el-popover>
        </div>
      <div style="padding: 5%"></div>
    </div>
  </div>
</template>


<script setup lang="ts">
import {onMounted, ref, h, computed, watch} from "vue";
import {getUser, postUser, deleteUser, updateUser, findByUserTitle, findByUserType} from "@/api/api";
import {ElMessage, ElMessageBox} from 'element-plus'
import {useLoginStore} from "@/stores";

const store = useLoginStore();

function haspermission(allowance: string[]) {
  return allowance.indexOf(store.role) !== -1;
}
const msg = ref("欢迎来到用户管理板块");
const options = [
  {
    label: '管理员',
    value: 'admin',
  },
  {
    label: '经理',
    value: 'manager',
  },
  {
    label: '用户',
    value: 'user',
  },
];

//增
const inputUser = ref({
  name:"",
  pwd:"",
  role:""
})

async function UserSubmit() {
  try {
    const response = await postUser(inputUser.value.name, inputUser.value.pwd);
    console.log(response);
    await loadUser();
    inputUser.value = {name: "", pwd: "", role:""};
  } catch (error) {
    console.error('Error loading User:', error);
  }
}


//delete
async function deleteUserAndHandleResponse(id: number) {
  try {
    const response = await deleteUser(id);
    console.log('User deleted successfully', response);
    await loadUser()
  } catch (error) {
    console.error('Error deleting User', error);
  }
}

const open_delete = (obj: any) => {
  ElMessageBox({
    title: '消息通知',
    message: h('p', null, [
      h('span', null, '请注意删除操作是不可逆的'),
      h('i', {style: 'color: teal'}, '数据库会同步变化'),
    ]),
    showCancelButton: true,
    confirmButtonText: '确认删除',
    cancelButtonText: '取消删除',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        deleteUserAndHandleResponse(obj.id);
        // window.location.reload()
        done();
      } else {
        done();
      }
    },
  }).then((action) => {
    ElMessage({
      type: 'info',
      message: `操作结果: ${action === 'confirm' ? '删除成功' : '已取消删除'}`,
    });
  });
}

//修改数据
const UserEdit = ref({
  name: "",
  pwd: "",
  role:"",
})

function setValue(obj: any) {
  UserEdit.value.name = obj.name;
  UserEdit.value.pwd = obj.pwd;
  UserEdit.value.role = obj.role;
}


async function handleEdit(obj: any) {
  try {
    const response = await updateUser(obj.id, UserEdit.value)
    console.log("User edit successfully", response)
    await loadUser()
    ElMessage({
      type: 'info',
      message: `操作结果:'修改成功'`,
    });
  } catch (error) {
    console.error(error);
  }
}

//查看所有
const User = ref([
  {id: 1, name: "", pwd: "", role:"",new_i: 0},
  {id: 2, name: "", pwd: "", role:"",new_i: 0},
])
let currentPage = ref(1)
const pageSize = ref(6)
const total = ref(User.value.length) // 计算总记录数

watch(User, (newValue) => {
  total.value = newValue.length;
});
const pagedUser = computed(() => {
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;

  return User.value.slice(startIndex, endIndex);
});

function handlePageChange(newPage: number) {
  currentPage.value = newPage
}

async function loadUser() {
  try {
    const response = await getUser();
    User.value = response.data;
    let new_index = 1;
    for (let oneUser of User.value) {
      oneUser.new_i = new_index;
      new_index++;
    }
  } catch (error) {
    console.error('Error loading User:', error);
  }
}

onMounted(() => {
  loadUser();
})

//特殊查找：
const name_pattern = ref('')
const role = ref('')
const suser = ref([
  {id: 1, name: "", pwd: "", role:"",new_id: 0},
])

async function findUser() {
  try {
    const response = await findByUserTitle(name_pattern.value);
    suser.value = response.data
    console.log(response)
    console.log(suser.value)
    let index = 1
    for (let i of suser.value) {
      i.new_id = index
      index++
    }
  } catch (error) {
    console.error("Error finding drug:", error);
  }
}
async function findUser2() {
  try {
    const response = await findByUserType(role.value);
    suser.value = response.data
    console.log(response)
    console.log(suser.value)
    let index = 1
    for (let i of suser.value) {
      i.new_id = index
      index++
    }
  } catch (error) {
    console.error("Error finding drug:", error);
  }
}
</script>


<style scoped>

</style>